package io.terminus.spzx.user.service.impl;

import com.alibaba.fastjson.JSON;
import io.terminus.spzx.common.config.exception.SpzxCustomException;
import io.terminus.spzx.consts.UserInfoConstant;
import io.terminus.spzx.model.dto.h5.UserLoginDto;
import io.terminus.spzx.model.dto.h5.UserRegisterDto;
import io.terminus.spzx.model.entity.user.UserInfo;
import io.terminus.spzx.model.vo.common.ResultCodeEnum;
import io.terminus.spzx.model.vo.h5.UserInfoVo;
import io.terminus.spzx.user.mapper.UserInfoMapper;
import io.terminus.spzx.user.service.UserInfoService;
import io.terminus.spzx.utils.AuthContextUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 会员用户Service实现类
 * @Date 2024-11-17
 */
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl implements UserInfoService {

    private final RedisTemplate<String, String> redisTemplate;

    private final UserInfoMapper userInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(UserRegisterDto userRegisterDto) {
        // 用户名就是手机号
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String validateCode = userRegisterDto.getCode();

        // 校验参数
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(nickName) || StringUtils.isEmpty(validateCode)) {
            throw new SpzxCustomException(ResultCodeEnum.DATA_ERROR);
        }

        // 校验短信验证码
        String cacheValidateCode = redisTemplate.opsForValue().get(UserInfoConstant.REDIS_SMS_VALIDATE_CODE_KEY_PREFIX + username);
        if (!validateCode.equals(cacheValidateCode)) {
            throw new SpzxCustomException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        UserInfo userInfo = userInfoMapper.getByUsername(username);
        if (Objects.nonNull(userInfo)) {
            throw new SpzxCustomException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        // 保存用户信息
        userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setNickName(nickName);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setPhone(username);
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfoMapper.save(userInfo);

        // 删除Redis中的数据
        redisTemplate.delete(UserInfoConstant.REDIS_SMS_VALIDATE_CODE_KEY_PREFIX + username);
    }

    @Override
    public String login(UserLoginDto userLoginDto) {
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();

        // 校验参数
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new SpzxCustomException(ResultCodeEnum.DATA_ERROR);
        }

        UserInfo userInfo = userInfoMapper.getByUsername(username);
        if (Objects.isNull(userInfo)) {
            throw new SpzxCustomException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 校验密码
        String md5InputPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5InputPassword.equals(userInfo.getPassword())) {
            throw new SpzxCustomException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 校验是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new SpzxCustomException(ResultCodeEnum.ACCOUNT_STOP);
        }

        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(UserInfoConstant.REDIS_USERINFO_TOKEN_KEY_PREFIX + token, JSON.toJSONString(userInfo), 30, TimeUnit.MINUTES);
        return token;
    }

    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
        UserInfoVo userInfoVo = new UserInfoVo();

        UserInfo userInfo = AuthContextUtil.getUserInfo();
        if (Objects.isNull(userInfo)) {
            String cacheUserInfo = redisTemplate.opsForValue().get(UserInfoConstant.REDIS_USERINFO_TOKEN_KEY_PREFIX + token);
            if (StringUtils.isEmpty(cacheUserInfo)) {
                throw new SpzxCustomException(ResultCodeEnum.LOGIN_AUTH);
            }
            userInfo = JSON.parseObject(cacheUserInfo, UserInfo.class);
        }

        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }
}
